package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

@Slf4j
@Component
public class RedisCacheClient {
    private final StringRedisTemplate stringRedisTemplate;

    public RedisCacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key, Object value, Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }

    public void setWithLogicalExpire(String key, Object value,Long time,TimeUnit unit){
        RedisData redisData=new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(redisData));
    }

    //缓存null值解决缓存穿透
    public <T,ID> T queryWithPassThrough(String keyPrefix, ID id, Class<T> type ,Function<ID, T> dbFallBack, Long time, TimeUnit unit){
        String key=keyPrefix+id;
        String s = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(s)){
            return JSONUtil.toBean(s,type);
        }
        if(s!=null){
            return null;
        }
        //数据库查询
        T t = dbFallBack.apply(id);
        if(t==null){
            set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        set(key,JSONUtil.toJsonStr(t),time,unit);
        return t;
    }

    private boolean tryLock(String lockKey){
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, lockKey, LOCK_SHOP_TTL, TimeUnit.MINUTES);
        return BooleanUtil.isTrue(aBoolean);
    }

    private void unLock(String lockKey){
        stringRedisTemplate.delete(lockKey);
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR=Executors.newFixedThreadPool(10);

    //解决缓存击穿问题（数据要存在且有逻辑过期时间，数据不存在redis当中直接返回null）
    public <T,ID> T queryWithLogicalExpire(String keyPrefix,ID id,Class<T> type,Function<ID,T> dbFallBack,Long time,TimeUnit unit){
        String key=keyPrefix+id;
        String s = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isBlank(s)){
            return null;
        }
        RedisData redisData=JSONUtil.toBean(s,RedisData.class);
        T t = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expire=redisData.getExpireTime();
        //判断数据是否过期
        if(expire.isAfter(LocalDateTime.now())){
            return t;
        }
        String lockKey=LOCK_SHOP_KEY+id;
        boolean b = tryLock(lockKey);
        if(b){
            //获取锁后再判断一次判断缓存是否已经被重建
            String s1 = stringRedisTemplate.opsForValue().get(key);
            RedisData redisData1 = JSONUtil.toBean(s1, RedisData.class);
            LocalDateTime expire1=redisData1.getExpireTime();
            if(expire1.isAfter(LocalDateTime.now())){
                T t1 = JSONUtil.toBean((JSONObject) redisData1.getData(), type);
                return t1;
            }
            //获取锁成功，开启新线程去执行缓存重建
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    //缓存重建
                    T apply = dbFallBack.apply(id);
                    this.setWithLogicalExpire(key,apply,time,unit);
                } catch (Exception e){
                    //缓存重建失败
                    log.error("id：{}的数据缓存重建失败",id);
                    throw new RuntimeException(e);
                }finally {
                    unLock(lockKey);
                }
            });
        }
        return t;
    }

}
